﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Runda.CMS.Bll;
using System.Data;
using Runda.CMS.Common.Utility;

namespace Runda.CMS.Portal.StockManagement
{
    public partial class QueryAccessoryStockDetail : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "AccessoryCode";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlVendor.BindDDDW(new CommonBll().dddw("vendor"), "vendor", "vendor");
                ddlVendor.Items.Add(new ListItem("--不限--", ""));
                ddlVendor.SelectedValue = "";
                Calculate();
                BindGrid();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Calculate();
            BindGrid();
        }

        protected void gridList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                LinkButton lnkbtnback = e.Item.FindControl("lnkbtnback") as LinkButton;
                HyperLink hlServiceBillNo = e.Item.FindControl("hlServiceBillNo") as HyperLink;
                Label lblCheckStatus = e.Item.FindControl("lblCheckStatus") as Label;
                Label lblOrderCheckStatus = e.Item.FindControl("lblOrderCheckStatus") as Label;

                DataRowView dv = e.Item.DataItem as DataRowView;
                if (base.CheckUserHasFuction(1, "Func6029") && dv["AccessoryStatusName"].ToString() == "借用")
                { lnkbtnback.Visible = true; }
                if (dv["RegisterID"].ToString() != null && dv["RegisterID"].ToString() !="")
                {
                    hlServiceBillNo.Text = "服务单";
                    hlServiceBillNo.NavigateUrl = "../ContractFollowUp/MaintainBasic.aspx?RegisterID=" + dv["RegisterID"].ToString();
                }
                if (dv["OrderCheckStatus"].ToString() != null && dv["OrderCheckStatus"].ToString() != "")
                {
                    lblOrderCheckStatus.Text = EnumeratorHelper.GetFieldText(((Enumerator.AccessoryReplacementCheckStatus)Convert.ToInt32(dv["OrderCheckStatus"].ToString())));
                }
                //lnkbtnView.Attributes.Add("onclick", "openMyFullWin('UserPerformanceView.aspx?UserID=" + dv["UserID"].ToString() + "', 'viewperformanceview');return false;");
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        private void Calculate()
        {
            string sqlwhere = "";
            sqlwhere = getWheresql();

            StockBll bll = new StockBll();
            DataTable dt = bll.CalcAccessoryStock(sqlwhere);

            if (dt != null && dt.Rows.Count > 0)
            {
                hfcount.Value = string.Format("{0:N}", dt.Rows[0]["countSum"]);
                hfquantitySum.Value = string.Format("{0:N}", dt.Rows[0]["countaccessory"]);
            }
            else
            {
                hfcount.Value = "0";
                hfquantitySum.Value = "0";
                
            }
        }

        private void BindGrid()
        {
            string sqlwhere = "";
            sqlwhere = getWheresql();

            StockBll bll = new StockBll();
            int RecordCount = 0;
            DataTable dt = bll.QueryAccessoryStockDetail(sqlwhere, SortString, AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, out RecordCount);
            gridList.DataSource = dt;
            gridList.DataBind();
            AspNetPager1.RecordCount = RecordCount;
        }

        protected void gridList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            Calculate();
            BindGrid();

        }


        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWheresql();

            StockBll bll = new StockBll();

            DataTable dt = bll.ExportAccessoryStock(Whereclause, " AccessoryCode asc ");

            Export.Export2Excel(dt, "配件明细", Page.Response);

        }

        private string getWheresql()
        {
            StringBuilder sb = new StringBuilder();
            if (txtUserName.Text != "")
            {
                sb.Append(" and (FactoryInstrumentCode like '%").Append(txtUserName.Text).Append("%' or CompanyInstrumentCode like  '%").Append(txtUserName.Text).Append("%')");
            }
            if (System.Convert.ToInt16(ddlAccessoryType.SelectedValue) > 0)
            {
                sb.Append(" and AccessoryType=" + ddlAccessoryType.SelectedValue.ToString());
            }
            if (ddlAccessoryStatus.SelectedValue!="")
            {
                sb.Append(" and AccessoryStatusName='" + ddlAccessoryStatus.SelectedValue.ToString() + "'");
            }

            if (ddlOrderCheckStatus.SelectedValue != "")
            {
                sb.Append(" and OrderCheckStatus=" + ddlOrderCheckStatus.SelectedValue.ToString() + "");
            }

            if (this.txtReceiverName.Text != "")
            { sb.Append(" and (ReceiverName like '%").Append(txtReceiverName.Text).Append("%')"); }

            if (OutStockDateFrom.SelectedDate != null)
            {
                sb.Append("and datediff(day,OutStockDate,'" + OutStockDateFrom.SelectedDate.Value.ToString() + "')<=0");
            }
            if (OutStockDateTo.SelectedDate != null)
            {
                sb.Append("and datediff(day,OutStockDate,'" + OutStockDateTo.SelectedDate.Value.ToString() + "')>=0");
            }
            if (AccessoryUsedDateFrom.SelectedDate != null)
            {
                sb.Append("and datediff(day,AccessoryUsedDate,'" + AccessoryUsedDateFrom.SelectedDate.Value.ToString() + "')<=0");
            }
            if (AccessoryUsedDateTo.SelectedDate != null)
            {
                sb.Append("and datediff(day,AccessoryUsedDate,'" + AccessoryUsedDateTo.SelectedDate.Value.ToString() + "')>=0");
            }
            if (ddlVendor.SelectedValue != "")
            {
                sb.Append(" and vendor  = '").Append(ddlVendor.SelectedValue.ToString()).Append("'");
            }
            
            if (this.txtAccessoryCode.Text != "")
            { sb.Append(" and (AccessoryCode like '%").Append(txtAccessoryCode.Text).Append("')"); }

            return sb.ToString();
        }

        protected void gridList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                
                string stockID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["StockID"].ToString();
                if (e.CommandName == "back")
                {
                    new StockBll().BackAccessory(stockID, base.CurrentUserEntity.UserName.ToString(), DateTime.Today);

                    BindGrid();
                }
                

            }
        }
    }
}